如果一个字符串由很多个完全相同的字符串组成,如果只想取其中一个则可以:

test.js:

let targetStr = process.argv.slice(2)[0]              // 获取想要重复的字符串  123456
let repeatCount = process.argv.slice(2)[1]            // 获取想要重复的次数    8
let resultStr = ''
for(let i = 0; i < repeatCount; i++) {
  resultStr += targetStr
}
console.log(resultStr)

function countInstances(mainStr, subStr)
{
    let count = 0
    let offset = 0
    do{
      offset = mainStr.indexOf(subStr, offset);
      if(offset != -1)
      {
          count++;
          offset += subStr.length;
      }
    } while (offset != -1)
    return count
}

function findTargetStr(targetStr) {
  let len = targetStr.length
  for(let i = 0; i < len; i++) {
    let str = ''
    for (let k = 0; k <= i; k++) {
      str += targetStr[k]
    }
    let count = countInstances(targetStr, str)
    if (count * str.length === len) {
      console.log(str)
      break
    }
  }
}

findTargetStr(resultStr)                         // 123456

shell命令窗口输入: node test.js 123456 8


hlongc
1 声望0 粉丝